package com.beney.server.handler;

import com.beney.codec.MessagePacketDecoder;
import com.beney.codec.MessagePacketEncoder;
import com.beney.message.MessageDispatcher;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class ServerHandlerInitializer extends ChannelInitializer<Channel> {
    /**
     * 等待读的时限
     */
    @Value("${netty.server.read-timeout}")
    private Integer readTimeout;

    @Autowired
    private ServerHandler serverHandler;

    @Autowired
    private MessageDispatcher messageDispatcher;

    @Override
    protected void initChannel(Channel ch) {
        // 获取 handler 列表
        ChannelPipeline pipeline = ch.pipeline();
        pipeline
                // 设置超时时间, 超过 timeout 则会抛出异常
                .addLast(new ReadTimeoutHandler(readTimeout, TimeUnit.SECONDS))
                // 编码器
                .addLast(new MessagePacketEncoder())
                // 解码器
                .addLast(new MessagePacketDecoder())
                // 消息分发器, 类似 SpringMVC ServletDispatcher
                .addLast(messageDispatcher)
                .addLast(serverHandler);
    }
}
